package com.quectel.mobile.controller.visitor;

import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.visitor.ApplyProcessingComponent;
import com.quectel.core.module.entranceguard.dto.EntranceGuardVisitorApplyRecordDto;
import com.quectel.core.module.entranceguard.dto.VisitorDto;
import com.quectel.core.module.entranceguard.service.EntranceGuardVisitorApplyRecordService;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.mobile.constants.MobileRedisCacheConstants;
import com.quectel.mobile.constants.MobileSecurityConstants;
import com.quectel.mobile.controller.BaseController;
import com.quectel.mobile.util.SessionHolder;
import com.quectel.mobile.vo.visitor.VisitorApplyVo;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import com.quectel.util.kit.IdKit;
import com.quectel.util.redis.RedisUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author rananxin
 * @email ryan.ran@quectel.com
 * @date 2022/1/19 10:15 上午
 */
@RestController
@RequestMapping("entranceGuardVisitorApplyRecord")
@Tag(name = "EntranceGuardVisitorApplyRecordController", description = "访客申请记录表相关api")
public class EntranceGuardVisitorApplyRecordController extends BaseController {

    @DubboReference
    private EntranceGuardVisitorApplyRecordService entranceGuardVisitorApplyRecordService;
    @DubboReference
    private VillageRoomService villageRoomService;
    @Autowired
    private ApplyProcessingComponent applyProcessingComponent;

    private static final Long VISITOR_APPLY_CT = 10L;
    private static final String ACCESSIBLE_SCOPES = "accessibleScopes";

    @PostMapping("apply")
    @Operation(summary = "访客申请")
    public Response<Object> apply(@RequestBody VisitorApplyVo visitorApplyVo) {
        SessionHolder.checkHousehold();

        long currentTimeMillis = System.currentTimeMillis();
        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();

        long incr = RedisUtils.incr(MobileRedisCacheConstants.VISITOR_APPLY_CT_KEY + currentHousehold.getId()
                , 1, 1, TimeUnit.DAYS);
        if (incr > VISITOR_APPLY_CT || incr < 0) {
            return Response.error("今日申请次数过多");
        }

        Long roomId = visitorApplyVo.getRoomId();
        VillageRoomDto villageRoomDto = villageRoomService.selectById(roomId);
        if (villageRoomDto == null) {
            return Response.error("不存在该房间");
        }

        VisitorDto visitor = CopyUtils.copyObj(visitorApplyVo, VisitorDto.class);
        visitor.setCreateTime(new Date(currentTimeMillis));

        EntranceGuardVisitorApplyRecordDto entranceGuardVisitorApplyRecordDto = CopyUtils.copyObj(visitorApplyVo, EntranceGuardVisitorApplyRecordDto.class);
        entranceGuardVisitorApplyRecordDto.setCreateTime(new Date(currentTimeMillis));
        entranceGuardVisitorApplyRecordDto.setTenantId(currentHousehold.getTenantId());

        entranceGuardVisitorApplyRecordDto.setFloorId(villageRoomDto.getFloorId());
        entranceGuardVisitorApplyRecordDto.setBuildingId(villageRoomDto.getBuildingId());
        entranceGuardVisitorApplyRecordDto.setVillageId(villageRoomDto.getVillageId());

        return applyProcessingComponent.applyHandler(visitor, entranceGuardVisitorApplyRecordDto
                , EntranceGuardVisitorApplyRecordDto.ApplyUserTypeEnum.HOUSEHOLD.getType(), currentHousehold.getId());
    }

    @GetMapping("list")
    @Operation(summary = "访客申请记录的分页查询列表")
    public Response<Page<EntranceGuardVisitorApplyRecordDto>> list(
            @Parameter(description = "小区") @RequestParam Long villageId,
            @Parameter(description = "有效范围 1过期 2生效中 3未到生效时间 eg: '1,2' ") @RequestParam String accessibleScopes,
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        SessionHolder.checkHousehold();

        HouseholdDto currentHousehold = SessionHolder.getLoginMobileUserSession().getCurrentHousehold();
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .put(LambdaUtil.getFieldName(EntranceGuardVisitorApplyRecordDto::getApplyUserId), currentHousehold.getId());

        if (StringUtils.isNotBlank(accessibleScopes)) {
            request.put(ACCESSIBLE_SCOPES, accessibleScopes.split(","));
        }

        int total = entranceGuardVisitorApplyRecordService.queryTotal(request.getParams());
        List<EntranceGuardVisitorApplyRecordDto> list = null;
        if (total > 0) {
            list = entranceGuardVisitorApplyRecordService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        long currentTimeMillis = System.currentTimeMillis();
        for (EntranceGuardVisitorApplyRecordDto dto : list) {
            dto.setEncryptId(IdKit.encryptByPrivateKey(dto.getId() + "", MobileSecurityConstants.DEFAULT_PRIVATE_KEY));
            dto.setId(null);


            if (currentTimeMillis < dto.getStartTime().getTime()) {
                dto.setAccessibleScope(EntranceGuardVisitorApplyRecordDto.AccessibleScopeEnum.NOT_EFFECT.getType());
            } else if (currentTimeMillis > dto.getEndTime().getTime()) {
                dto.setAccessibleScope(EntranceGuardVisitorApplyRecordDto.AccessibleScopeEnum.OVERDUE.getType());
            } else {
                dto.setAccessibleScope(EntranceGuardVisitorApplyRecordDto.AccessibleScopeEnum.EFFECT.getType());
            }
        }

        Page<EntranceGuardVisitorApplyRecordDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<EntranceGuardVisitorApplyRecordDto>>ok().wrap(page);
    }


    @GetMapping("info/{encryptId}")
    @Operation(summary = "查询访客申请记录详情")
    public Response<EntranceGuardVisitorApplyRecordDto> info(@PathVariable("encryptId") String encryptId) {
        Long id = Long.parseLong(IdKit.decryptByPublicKey(encryptId, MobileSecurityConstants.DEFAULT_PUBLIC_KEY));

        EntranceGuardVisitorApplyRecordDto entranceGuardVisitorApplyRecordDto = entranceGuardVisitorApplyRecordService.selectById(id);

        return Response.<EntranceGuardVisitorApplyRecordDto>ok().wrap(entranceGuardVisitorApplyRecordDto);
    }
}
